package command

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

type ViewCommand struct{}

func (i *ViewCommand) Desc() *CommandDesc {
	return &CommandDesc{
		Name: "view",
		Methods: []*CommandMethod{
			{
				Name: "create",
				Desc: "创建视图",
				Params: []*CommandParams{
					{Name: "path", Desc: "view 目录，项目根目录相对路径"},
				},
			},
		},
	}
}

func (i *ViewCommand) Create(path string) {
	ParamCheck("path", path)

	path = strings.TrimRight(path, "/")

	currentDir := GetCurrentDir()
	project, err := ProjectName()
	HandleError(err)

	defer BeautifyImports()

	pkg := filepath.Base(path)
	output := fmt.Sprintf("%s/views.go", path)
	command := fmt.Sprintf("go-bindata-assetfs -pkg %s -o %s %s/...", pkg, output, path)
	Exec(command, currentDir)
	// 处理生成文件的bug
	outputFilePath := filepath.Clean(fmt.Sprintf("%s/%s", currentDir, output))
	outputContentBytes, err := os.ReadFile(outputFilePath)
	HandleError(err)
	outputContent := strings.ReplaceAll(string(outputContentBytes), "\t\"io\"", "\t\"io\"\n\t\"os\"")
	if !strings.Contains(outputContent, "assetfs \"github.com/elazarl/go-bindata-assetfs\"") && strings.Contains(outputContent, "\"github.com/elazarl/go-bindata-assetfs\"") {
		outputContent = strings.ReplaceAll(outputContent, "\"github.com/elazarl/go-bindata-assetfs\"", "assetfs \"github.com/elazarl/go-bindata-assetfs\"")
	}
	err = os.WriteFile(outputFilePath, []byte(outputContent), 0755)
	HandleError(err)

	autoloadFilePath := filepath.Clean(fmt.Sprintf("%s/autoload/View.go", currentDir))
	autoloadContentBytes, err := os.ReadFile(autoloadFilePath)
	HandleError(err)

	autoloadContent := string(autoloadContentBytes)
	importContent := fmt.Sprintf("\"%s/%s\"", project, path)
	if strings.Contains(autoloadContent, importContent) {
		return
	}

	autoloadContent = strings.ReplaceAll(autoloadContent, "\"gitee.com/csingo/cServer\"", fmt.Sprintf("\"gitee.com/csingo/cServer\"\n\t%s", importContent))
	autoloadContent = strings.ReplaceAll(autoloadContent, "func InjectView() {", fmt.Sprintf("func InjectView() {\n\tcServer.Inject(&assetfs.AssetFS{\n\t\tAsset:     %s.Asset,\n\t\tAssetDir:  %s.AssetDir,\n\t\tAssetInfo: nil,\n\t\tPrefix:    \"%s\",\n\t\tFallback:  \"\",\n\t})", pkg, pkg, path))
	autoloadContent = strings.ReplaceAll(autoloadContent, "\n\n", "\n")
	err = os.WriteFile(autoloadFilePath, []byte(autoloadContent), 0755)
	HandleError(err)

	// 格式化文件
	Exec(fmt.Sprintf("go fmt %s", autoloadFilePath), currentDir)
}
